import { Request, Response, NextFunction } from 'express';
import { UserService } from "../services/user.service";
import { ResponseWrapper } from '../../framework/utils/ResponseWrapper';
import { NotFoundError } from '../../framework/utils/AppError';
/**
 * catchAsync 是一个高阶函数，用于捕获异步函数中的错误，并将它们传递给 Express 的下一个错误处理中间件。
 * 在 Express 中，如果异步函数内部发生错误，并且没有自己捕获，Express 不会自动捕获这些错误，从而导致未处理的 Promise 拒绝。
 * 使用 catchAsync 可以避免为每个异步控制器编写 try-catch 块，使代码更简洁，并确保所有错误都通过错误处理中间件统一处理。
 */
import { catchAsync } from '../../framework/utils/catchAsync';

export class UserController {
  private userService: UserService;

  constructor() {
    this.userService = new UserService();
  }

  getAllUsers = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
    const users = await this.userService.getAllUsers();
    ResponseWrapper.success(res, users, '用户列表获取成功');
  });

  getUserById = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
    const user = await this.userService.getUserById(req.params.id);
    if (!user) {
      throw new NotFoundError('用户不存在');
    }
    ResponseWrapper.success(res, user, '用户信息获取成功');
  });

  createUser = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
    const user = await this.userService.createUser(req.body);
    ResponseWrapper.created(res, user, '用户创建成功');
  });

  updateUser = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
    const user = await this.userService.updateUser(req.params.id, req.body);
    if (!user) {
      throw new NotFoundError('用户不存在');
    }
    ResponseWrapper.success(res, user, '用户更新成功');
  });

  deleteUser = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
    const result = await this.userService.deleteUser(req.params.id);
    if (!result) {
      throw new NotFoundError('用户不存在');
    }
    ResponseWrapper.success(res, null, '用户删除成功');
  });
}